package com.rd.p2p.service;

import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.qdlc.p2p.biz.processor.task.AbstractTaskProcessor;
import com.qdlc.p2p.common.core.queue.TaskProcessorException;
import com.qdlc.p2p.common.core.queue.ValueEvent;

@Service
@Transactional
public class SendTemplateMessageTaskProcessor extends AbstractTaskProcessor {
	private static Logger LOG = LoggerFactory.getLogger(SendTemplateMessageTaskProcessor.class);

	@Override
	public boolean supports(ValueEvent event) {
		return event instanceof SendTemplateMessageEvent;
	}

	@Override
	public void process0(ValueEvent event) throws TaskProcessorException {
		SendTemplateMessageEvent messageEvent = (SendTemplateMessageEvent) event;
		WeixinProxy wp = new WeixinProxy();
		TemplateMessage tm = new TemplateMessage(messageEvent.getToUser(), messageEvent.getTemplateId(),
				messageEvent.getTitle(), messageEvent.getUrl());
		if (messageEvent.getData() != null) {
			for (Entry<String, String> entry : messageEvent.getData().entrySet()) {
				tm.pushData(entry.getKey(), entry.getValue());
			}
		}
		try {
			wp.sendTmplMessage(tm);
			LOG.debug("发送微信信息至:" + messageEvent.getToUser());
		} catch (WeixinException e) {
			LOG.error("SendTemplateMessageTaskProcessor::process0() 出现异常： " + e);
		}
	}

}
